import { Component, Vue, Watch } from 'vue-property-decorator' // @ is an alias to /src
import style from './UserInfo.less'
import { State, Action, Mutation } from 'vuex-class'
import { RootState } from '@/store'
import { desensitization } from '../lib/utils'
import { ElForm } from 'element-ui/types/form'

const checkName = (rule: any, value: any, callback: any) => {
  const reg = /([0-9]$)|(([a-zA-Z+\\.?\\·?a-zA-Z+]{1,20}$)|([\u4e00-\u9fa5+\\·?\u4e00-\u9fa5+]{1,20}$))/ // 仅支持中英文与阿拉伯数字 支持“·”分割 最大长度不超过20位
  if (!reg.test(value)) {
    return callback(new Error('请输入正确的姓名'))
  }
  callback()
}

const userRule = {
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {
      pattern: /^1[0-9]{10}$/,
      message: '手机号格式不正确',
      trigger: 'blur',
    },
  ],
  name: [
    { required: true, message: '请输入申请人姓名', trigger: 'blur' },
    {
      min: 1,
      max: 20,
      message: '长度在 1 到 20 个字符',
      trigger: 'blur',
    },
    { validator: checkName, trigger: 'blur' },
  ],
  code: [
    { required: true, message: '请输入手机验证码', trigger: 'blur' },
    { len: 6, message: '长度不正确', trigger: 'blur' },
  ],
  email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }],
  licenseNumber: [
    { required: true, message: '请输入身份证号码', trigger: 'blur' },
    {
      pattern: /^(([0-9]{14})|([0-9]{17}))([0-9]|X|x)$/,
      message: '身份证格式不正确',
      trigger: 'blur',
    },
  ],
}

@Component({})
export default class UserInfo extends Vue {
  @State((state: RootState) => state.user.accountName)
  private name!: string
  @State((state: RootState) => state.user.organizeName)
  private departmentName!: string
  @State((state: RootState) => state.user.accountLicenseNumber)
  private licenseNumber!: string
  @State((state: RootState) => state.user.accountMobile)
  private accountMobile!: string
  @State((state: RootState) => state.user.accountEmail)
  private email!: string
  @State((state: RootState) => state.user.dingUserId)
  private dingUserId!: string

  @Action('user/info') private userInfo!: any
  @Action('user/sendMobileCode') private sendMobileCode!: any
  @Action('user/saveInfo') private saveInfo!: any
  @Mutation('user/setStateData') private setStateData!: any
  @Action('login/logout') private logout!: any

  private edit: boolean = false
  private userData: any = {
    name: '',
    licenseNumber: '',
    mobile: '',
    code: '',
    email: '',
  }
  private loading = false
  private timer: any = null
  private countDownTime: number = 0
  private gotoLigonTimer: number = 0
  private sendDisabled: boolean = false

  get detailForm() {
    return (
      <el-form class="info-form" label-position="left">
        <el-form-item label="姓名" label-width="68px">
          <span>{this.name}</span>
        </el-form-item>
        <el-form-item label="身份证号" label-width="68px">
          <span>{desensitization(this.licenseNumber)}</span>
        </el-form-item>
        <el-form-item label="邮箱" label-width="68px">
          <span>{this.email}</span>
        </el-form-item>
        <el-form-item label="手机号码" label-width="68px">
          <span>{desensitization(this.accountMobile)}</span>
        </el-form-item>
        <el-button type="primary" class="primary" onClick={this.quit}>
          退出登录
        </el-button>
      </el-form>
    )
  }

  get editForm() {
    return (
      <el-form
        {...{ props: { model: this.userData, rules: userRule } }}
        ref="userForm"
        hide-required-asterisk
        class={style.editForm}
      >
        <el-form-item prop="name" label="姓名" label-width="72px">
          <el-input
            v-model={this.userData.name}
            placeholder="请输入姓名"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item prop="licenseNumber" label="身份证号" label-width="72px">
          <el-input
            v-model={this.userData.licenseNumber}
            placeholder="请输入身份证号码"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item prop="email" label="邮箱" label-width="72px">
          <el-input
            v-model={this.userData.email}
            placeholder="请输入邮箱"
            maxlength="30"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item prop="mobile" label="手机号码" label-width="72px">
          <el-input
            v-model={this.userData.mobile}
            placeholder="请输入手机号"
            disabled
            autocomplete="off"
          />
          <el-button
            type="text"
            onClick={() => {
              this.$router.push({
                name: 'mobileUpdate',
                params: { type: 'userInfo' },
              })
            }}
          >
            更换手机号
          </el-button>
        </el-form-item>
        <el-form-item
          prop="code"
          class="code-item"
          label="验证码"
          label-width="72px"
        >
          <el-input
            class="input-code"
            v-model={this.userData.code}
            placeholder="请输入手机验证码"
            autocomplete="off"
          />
          <button
            class={style.mobileCode}
            onClick={this.getMobileCode}
            disabled={!!this.countDownTime || this.sendDisabled}
          >
            {this.countDownTime ? `${this.countDownTime}s` : '发送验证码'}
          </button>
        </el-form-item>
        <p class="footer">
          <el-button
            type="primary"
            class={[
              { 'btn-primary': true, 'btn-primary-hover': this.validField() },
            ]}
            loading={this.loading}
            onClick={() => {
              this.save()
            }}
          >
            确认修改
          </el-button>
          <el-button
            onClick={() => {
              this.edit = false
            }}
          >
            取消
          </el-button>
        </p>
      </el-form>
    )
  }

  protected render(h: any) {
    return (
      <div class={style.container}>
        <div class={style.left}>
          <div class={style.card}>
            <p>
              <img src={require('@/assets/avatar.png')} alt="头像" />
            </p>
            <p>
              姓名：<span class={style.name}>{this.name}</span>
            </p>
          </div>
        </div>
        <div class={style.right}>
          <p class={style.title}>
            浙政钉信息{' '}
            <el-button type="text" onClick={this.toBind}>
              {this.dingUserId ? '重新绑定' : '绑定'}
            </el-button>
          </p>
          <el-form class="info-form" label-position="left">
            <el-form-item label="浙政钉ID" label-width="68px">
              <span>{this.dingUserId} </span>
            </el-form-item>
          </el-form>
          <p class={style.title}>
            资料信息
            {!this.edit && (
              <el-button type="text" onClick={this.toEdit}>
                编辑
              </el-button>
            )}
          </p>
          <div v-show={!this.edit}>{this.detailForm}</div>
          <div v-show={this.edit}>{this.editForm}</div>
        </div>
      </div>
    )
  }

  @Watch('edit')
  private editChange(val: boolean) {
    if (!val) {
      this.countDownTime = 0
      this.sendDisabled = false
      this.timer && clearInterval(this.timer)
    }
  }
  @Watch('name', { deep: true, immediate: true })
  private userInfoChange(val: any) {
    if (this.edit) {
      this.toEdit()
    }
  }

  private validField() {
    return (
      !!this.userData.name &&
      !!this.userData.licenseNumber &&
      !!this.userData.mobile &&
      !!this.userData.code
    )
  }

  private toEdit() {
    !!(this.$refs.userForm as ElForm) &&
      (this.$refs.userForm as ElForm).clearValidate()
    this.userData = {
      name: this.name || '',
      licenseNumber: this.licenseNumber || '',
      mobile: this.accountMobile || '',
      code: '',
      email: this.email || '',
    }
    this.edit = true
  }

  private getMobileCode(e: Event) {
    e.stopPropagation()
    e.preventDefault()
    let hasErr = false

    // this.loginData.mobileCode = ''

    const from = this.$refs.userForm as ElForm
    from.validateField(['mobile', 'licenseNumber', 'name'], data => {
      if (!!data) {
        hasErr = true
      }
    })

    if (hasErr) return
    this.sendDisabled = true

    this.sendMobileCode(this.userData)
      .then((res: any) => {
        this.sendDisabled = false

        if (!this.countDownTime) {
          // 倒计时 90s
          this.countDown(90, (time: number) => {
            this.countDownTime = time
          })
        }
      })
      .catch((e: any) => {
        this.sendDisabled = false
      })
  }

  private countDown(times: number, step?: any, cb?: any) {
    let time = times
    if (step) step(time)
    this.timer && clearInterval(this.timer)
    this.timer = setInterval(() => {
      if (time <= 0) {
        this.timer && clearInterval(this.timer)
        if (cb) cb()

        return
      }

      time--
      if (step) step(time)
    }, 1000)
  }

  private mounted() {
    this.edit = !!this.$route.query.edit
    this.$router.replace({ name: 'userInfo' })
  }

  private async quit() {
    await this.logout()
    this.$router.push({ name: 'homepage' })
  }

  private save() {
    ;(this.$refs.userForm as ElForm) &&
      (this.$refs.userForm as ElForm).validate((val: boolean) => {
        if (val) {
          this.loading = true
          this.saveInfo({
            name: this.userData.name,
            idCard: (this.userData.licenseNumber || '').toUpperCase(),
            mobileCode: this.userData.code,
            email: this.userData.email,
          })
            .then((res: any) => {
              this.loading = false
              this.userInfo()
              this.edit = false
            })
            .catch((e: any) => {
              this.loading = false
            })
        }
      })
  }

  private toBind() {
    this.setStateData({ bindDingUserVisible: true })
  }
}
